import { defineStore } from 'pinia';
import axios from 'axios';
import request from '../utils/request';
import router from '../router';


// 问题数据类型定义
export interface Question {
  id: number;
  title: string;
  content: string;
  user_id: number;
  category_id: number;
  is_solved: boolean;
  like_count: number;
  view_count: number;
  created: string;
  updated: string;
  username: string;
  avatar?: string;
  answer_count?: number;
}
  //问题预览接口
export interface QuestionSimplify{
  id: number,
  title: string,
  username: string,
  view_count: number,
  answer_count: number,
  is_solved: number,
  questionname: string,
  created: Date
}

// 回答数据类型定义
export interface Answer {
  id: number;
  user_id: number;
  content: string;
  is_accepted: number;
  like_count: number;
  created_at: string;

  username: string;
  avatar?: string;

}

// 分页信息类型
interface Pagination {
  currentPage: number;
  pageSize: number;
  total: number;
  totalPages:number;
}

// 定义Store
export const useQuestionStore = defineStore('question', {
  state: (): {
    hotQuestions: Question[];
    latestQuestions: Question[];
    currentQuestion: Question | null;
    questionAnswers: Answer[];
    questionSimplify:QuestionSimplify[];
    loading: boolean;
    error: string | null;
    pagination: Pagination;
    questionDetailId:number;
  } => ({
    hotQuestions: [],
    latestQuestions: [],
    currentQuestion: null,
    questionSimplify:[],
    questionAnswers: [],
    loading: false,
    error: null,
    pagination: {
      currentPage: 1,
      pageSize: 15,
      total: 0,
      totalPages:1
    },
    questionDetailId:0
  }),

  getters: {
    // 计算未解决的问题数量
    unresolvedCount: (state) => {
      return state.latestQuestions.filter(q => !q.is_solved).length;
    },
    
    // 获取当前问题的最佳回答
    bestAnswer: (state) => {
      return state.questionAnswers.find(answer => answer.is_accepted) || null;
    },
    
    // 获取当前页的问题列表（结合分页）
    currentPageQuestions: (state) => {
      const startIndex = (state.pagination.currentPage - 1) * state.pagination.pageSize;
      return state.latestQuestions.slice(startIndex, startIndex + state.pagination.pageSize);
    }
  },

  actions: {
    //接收准备查看的问题的ID并跳转
    async checkThisQuestionDetail(Qid:number){
      if(Qid!==this.questionDetailId)
      {
        this.questionDetailId=Qid;
      }
      
      await router.push({
        name:'questionDetail',
        params:{
          id:this.questionDetailId
        }
      });

      this.questionDetailId=0
    },
    // 获取热门问题
    async fetchHotQuestions(limit: number = 10): Promise<void> {
      try {
        this.loading = true;
        this.error = null;
        const response = await axios.get<Question[]>(`/api/questions/hot?limit=${limit}`);
        this.hotQuestions = response.data;
      } catch (err) {
        this.error = err instanceof Error ? err.message : '获取热门问题失败';
        console.error('获取热门问题错误:', this.error);
      } finally {
        this.loading = false;
      }
    },

    

    // 获取问题的简化版
    async getQuestionSimplify(){
        try{
            const response = await request.get('/api/questions/simplify',
              {page:this.pagination.currentPage,
                limit:this.pagination.pageSize,
                sort:'created',
                order:'DESC'});

            this.questionSimplify=response.data;
            this.pagination.total=response.count;
            this.pagination.currentPage=response.currentPage;
            this.pagination.totalPages=response.totalPages;
        }catch(err){
            this.error = err instanceof Error ? err.message :'获取问题预览失败'
            console.error('获取问题预览错误:', this.error);
        }
    },

    // 获取问题详情
    async fetchQuestionDetail(id: number,pageNumber?:number,pageSize?:number,order?:String): Promise<void> {
      if (!id) {
        this.error = '问题ID不能为空';
        return;
      }

      try {
        this.error = null;
        
        // 并行请求问题详情和回答
        const [questionRes, answersRes] = await Promise.all([
          request.get(`api/questions/${id}`),
          request.get(`/api/answers/question/${id}`,
            { 
              page:pageNumber,
              limit:pageSize,
              order:order
            }
          )
        ]);
        
        this.currentQuestion = questionRes.data;
        this.questionAnswers = answersRes.data;



      } catch (err) {
        this.error = err instanceof Error ? err.message : '获取问题详情失败';
        console.error('获取问题详情错误:', this.error);
      }
    },

    // 重置当前问题数据
    resetCurrentQuestion(): void {
      this.currentQuestion = null;
      this.questionAnswers = [];
    },

    // 重置所有状态
    resetAll(): void {
      this.hotQuestions = [];
      this.latestQuestions = [];
      this.currentQuestion = null;
      this.questionSimplify=[];
      this.questionAnswers = [];
      this.error = null;
      this.pagination = {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        totalPages:1
      };
    }
  }
});
    